import {getToday} from "../../utils/date";
import {getLocal} from "../../utils/local";

export async function uploadImageOne(localFile) {
    var name = getToday() + "/" + localFile.name
    var file = new AV.File(name, localFile)
    /*获取图片大小*/
    var reader = new FileReader();
    reader.readAsDataURL(localFile);
    var sizeResult = await  new Promise((resolve) => {
        reader.onload = function (e) {
            var image = new window.Image()
            image.src = e.target.result
            return new Promise(() => {
                image.onload = () => {
                    return resolve({width: image.width, height: image.height})
                }
            })
        }
    })

    var userPointer = AV.Object.createWithoutData('user', getLocal('app.login_user').objectId);
    var userImageDao = new AV.Object('userImage');// 构建 Comment 对象
    userImageDao.set("image", file)
    userImageDao.set("user", userPointer)
    var userImageInsertResult = (await  userImageDao.save()).toJSON()
    return {
        ...userImageInsertResult,
        user: {
            objectId: getLocal('app.login_user').objectId
        },
        ...sizeResult//注入width heigh
    }
}

export async function uploadImages(files, {onProgress, onComplete}) {
    /*0-1*/
    var all_length = files.length
    var _array = []
    for (var i = 0; i < all_length; i++) {
        var file = files[i]
        var imageObj = await  uploadImageOne(file)
        _array.push(imageObj)
        onProgress && onProgress(i, imageObj)
    }
    onComplete && onComplete(_array)

}